package com.xiaolin.session.interceptor;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName LoginInterceptor
 * @Description 请求拦截器
 * @Detail detail
 * @Author MyPC
 * @Date 2020/10/7
 * @Version 1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取session
        HttpSession session = request.getSession();
        String userInfo = (String) session.getAttribute("userInfo");
        Cookie[] cookies = request.getCookies();
        boolean flag=false;
        for (Cookie cookie : cookies) {
            //判断用户cookie是否存在，即是否登录过
            String value = cookie.getValue();
            String username = (String) session.getAttribute(value);
            if(StringUtils.isNotEmpty(username) && username.equals(userInfo)){
                flag=true;
                break;
            }
        }
        if(flag){
            return true;
        }else {
            try {
                response.sendRedirect(request.getContextPath()+"/login.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
